<template>
  <!-- 资产型号表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="750px"
    draggable
    @close="closeDialog"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100"
      v-show="!props.isReadonly"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="型号" prop="modelNo">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.modelNo"
              placeholder="请输入型号"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="类型" prop="assetTypeId">
            <!-- <el-input
              v-if="!props.isReadonly"
              v-model="formData.assetTypeId"
              placeholder="请输入类型"
              clearable
            /> -->
            <el-tree-select
              v-if="!props.isReadonly"
              placeholder="请选择类型"
              v-model="formData.assetTypeId"
              :data="catalogList"
              node-key="id"
              :props="{
                label: 'assetTypeName',
                value: 'id',
                children: 'nodes',
              }"
              :render-after-expand="false"
              :check-strictly="true"
              style="width: 300px"
              clearable
            />
            <span v-else>{{ formData.assetTypeName }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="品牌" prop="brandId">
            <el-select
              v-model="formData.brandId"
              placeholder="请选择品牌"
              clearable
              v-if="!props.isReadonly"
              style="width: 300px"
              @change="changeBrand"
            >
              <el-option
                v-for="item in brandList"
                :key="`${item.id}`"
                :label="`${item.brandCode}-${item.brandName}`"
                :value="`${item.id}`"
              />
            </el-select>
            <span v-else>{{ formData.brandName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="制造商" prop="makerId">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.makerName"
              placeholder="请输入制造商"
              clearable
              disabled
            />

            <span v-else
              >{{ formData.makerCode }}-{{ formData.makerName }}</span
            >
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.remarks"
              placeholder="请输入备注"
              clearable
            />

            <span v-else>{{ formData.remarks }}</span>
          </el-form-item>
        </el-col>
        <el-form-item label="启用状态" prop="enabled">
          <el-radio-group v-model="formData.enabled" v-if="!props.isReadonly">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>

          <span v-else>{{ formData.enabled == 1 ? "启用" : "停用" }}</span>
        </el-form-item>
      </el-row>
    </el-form>
    <el-descriptions
      v-show="props.isReadonly"
      class="margin-top"
      :column="2"
      size="large"
      border
    >
      <el-descriptions-item class-name="myConten">
        <template #label>
          <div class="cell-item">型号</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.modelNo }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">类型</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.assetTypeName }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">品牌</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.brandCode }}-{{ formData.brandName }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">制造商</div>
        </template>
        {{ formData.makerName }}
      </el-descriptions-item>

      <el-descriptions-item :span="2">
        <template #label>
          <div class="cell-item">是否启用</div>
        </template>
        <el-tag v-show="formData.enabled === 1" type="">启用</el-tag>
        <el-tag v-show="formData.enabled !== 1" type="info">停用</el-tag>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">备注</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.remarks || "暂无备注" }}
        </div>
      </el-descriptions-item>
    </el-descriptions>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "EQUDEVICEMODELEDITE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  assetTypeIdTree: {
    type: String,
    default: () => {
      return "";
    },
  },
  assetKind: {
    type: Number,
    default: null,
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    if (props.assetTypeIdTree) {
      formData.assetTypeId = props.assetTypeIdTree;
      catalogList.value.forEach((item) => {
        if (item.id == props.assetTypeIdTree) {
          formData.assetTypeName = item.assetTypeName;

          return;
        } else {
          if (item.nodes.length > 0) {
            catalogList1(item.nodes);
          }
        }
      });
    }
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);
watch(
  () => props.assetKind,
  (newVal: number) => {},
  {
    immediate: true,
  }
);
const catalogList1 = (item) => {
  if (item.length > 0) {
    item.forEach((item1) => {
      if (item1.id == props.assetTypeIdTree) {
        formData.assetTypeName = item1.assetTypeName;

        return;
      } else {
        catalogList1(item1.nodes);
      }
    });
  }
};
const rules = reactive({
  version: [],
  assetKind: [],
  assetTypeId: [{ required: true, message: "请选择类型", trigger: "change" }],

  brandId: [{ required: true, message: "请选择品牌", trigger: "change" }],
  modelNo: [{ required: true, message: "请输入型号", trigger: "change" }],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  organizationId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  createTime: [],
  createdUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  createdUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  lastUpdateTime: [],
  lastUpdatedUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  lastUpdatedUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  enabled: [],
  deleted: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  assetKind: props.assetKind,
  assetTypeId: "",
  assetTypeName: "",
  makerId: "",
  makerName: "",
  makerCode: "",
  brandId: "",
  brandName: "",
  brandCode: "",
  modelNo: "",
  remarks: "",
  organizationId: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        assetKind,
        assetTypeId,
        assetTypeName,
        makerCode,
        makerId,
        makerName,
        brandId,
        brandName,
        brandCode,
        modelNo,
        remarks,
        organizationId,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        assetKind,
        assetTypeId,
        assetTypeName,
        makerId,
        makerName,
        makerCode,
        brandId,
        brandCode,
        brandName,
        modelNo,
        remarks,
        organizationId,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.assetKind = props.assetKind;
  formData.assetTypeId = "";
  formData.assetTypeName = "";
  formData.makerId = "";
  formData.makerName = "";
  formData.makerCode = "";
  formData.brandId = "";
  formData.brandName = "";
  formData.brandCode = "";
  formData.modelNo = "";
  formData.remarks = "";
  formData.organizationId = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
}

const loading = ref(false);

/** 资产型号保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/eam/eamAssetModel/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 目录树
const catalogList: any = ref([]);

// 获取内容树数据
const getCAtalogList = async () => {
  // 获取内容树
  await request({
    url: "eam/eamAssetType/getAvailableTree",
    method: "POST",
    data: { assetKind: props.assetKind },
  }).then((res) => {
    catalogList.value = res.data;
  });
};

// 获取资产品牌数据
const brandList: any = ref([]);
const getBrandList = async () => {
  await request({
    url: "eam/eamassetbrand/getList",
    method: "post",
    data: { assetKind: props.assetKind },
  }).then((res) => {
    brandList.value = res.data;
    console.log(res.data);
  });
};

// 选择品牌
const changeBrand = (e) => {
  formData.makerId = "";
  if (e) {
    brandList.value.forEach((element) => {
      if (e == element.id) {
        formData.makerId = element.makerId;
        formData.brandCode = element.brandCode;
        formData.makerName = element.makerName;
      }
    });
  } else {
    formData.makerId = "";
    formData.brandCode = "";
    formData.makerName = "";
  }
};
onMounted(() => {
  getCAtalogList();
  getBrandList();
}),
  // 组件销毁时调用
  onBeforeUnmount(() => {
    visibleDialog.value = false;
    emit("change-visible", false);
  });
</script>
<style scoped lang="scss">
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 120px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
}
</style>
